#include "Protocol.hpp"
#include "TcpServer.hpp"
#include "Socket.hpp"
#include "Calculate.hpp"
#include <unistd.h>
#include <iostream>
#include <memory>
using namespace Net_Work;
using namespace Protocol;
using namespace CalCulateNS;

//网络负责IO发送
//HandlerRequest字节流数据解析和调用业务处理方法的

std::string HandLerRequest(std::string &inbufferstream, bool *error_code)
{
    *error_code = true;
    //0.计算机对象
    Calculate calculate;
    //std::string inbufferstream;

    //1.构建响应对象
    std::unique_ptr<Factory> factory(new Factory);
    auto req = factory->BuildRequest();

    // 2.分析字节流,看是否有一个完整的报文
    std::string total_resp_string;
    std::string message;
    while(Decode(inbufferstream, &message))
    {

        std::cout << "Decode message" << message << std::endl;
   
    // 3.我一定读到了一个完整的报文，可以进行反序列化
    if (!req->Deserialize(message))
    {
        *error_code = false;
        std::cerr << "Failed to deserialize request" << std::endl;
        return std::string();

    }

    // 4.业务处理
    auto resp = calculate.Cal(req);

    // 5.序列化response
    std::string send_string;
    resp->Serialize(&send_string);

    // 6.构建完成的字符串级别的响应报文
    send_string = Encode(send_string);

    // 7.发送
    total_resp_string += send_string;
    //std::cout << "Encoded response: " << send_string << std::endl;
    }
    return total_resp_string;

    
}

//.serever port
//服务器主函数
int main(int argc, char *argv[])
{
    if(argc != 2)
    {
        std::cout << "Usage: " << argv[0] << " port" << std::endl;
        return 0;        
    }
    uint16_t localport = std::stoi(argv[1]);
    std::unique_ptr<TcpServer> svr (new TcpServer(localport, HandLerRequest));
    svr->loop();    
    return 0;

}